package com.csu.csumall.controller.frontend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.Shipping;
import com.csu.csumall.entity.User;
import com.csu.csumall.service.IShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static com.csu.csumall.common.Constant.ORIGIN;


@RestController
@RequestMapping("/api/shipping")
@CrossOrigin(origins = ORIGIN)
public class ShippingController {

    private final IShippingService shippingService;

    @Autowired
    public ShippingController(IShippingService shippingService) {
        this.shippingService = shippingService;
    }

    /**
     * 列出收货信息
     *
     * @return 已登录用户全部收货地址
     */
    @GetMapping(produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> list(@AuthenticationPrincipal User user) {

        List<Shipping> shippingList = shippingService.list(
                new QueryWrapper<Shipping>().eq("user_id", user.getId())
                        .ne("status", ItemStatus.DISABLE.getValue())
        );
        shippingList.forEach(shipping -> {
            shipping.setStatus(null);
            shipping.setCreateTime(null);
            shipping.setUpdateTime(null);
        });
        return new ResponseEntity<>(UniformResponse.createForSuccess(shippingList), HttpStatus.OK);
    }

    /**
     * 列出收货信息
     *
     * @param id 必选
     * @return 已登录用户全部收货地址；已登录用户特定收货地址；未登录的错误信息
     */
    @GetMapping(value = "{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> get(@AuthenticationPrincipal User user,
                                                       @PathVariable(value = "id", required = false) Integer id) {


        Shipping shipping = shippingService.getOne(
                new QueryWrapper<Shipping>().eq("id", id).eq("user_id", user.getId())
                        .ne("status", ItemStatus.DISABLE.getValue())
        );
        if (null == shipping) {
            return new ResponseEntity<>(UniformResponse.createForError("未找到"), HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(UniformResponse.createForSuccess(shipping), HttpStatus.OK);
        }
    }

    /**
     * 通过Shipping对象新增收货信息，为null的属性不更新
     *
     * @param shipping 收货地址对象，部分属性可空，部分属性必选，详情查看代码
     * @return 未登录的错误信息；必选属性为空的错误信息；创建成功的Shipping对象；创建失败的错误信息
     */
    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<UniformResponse<Shipping>> post(@RequestBody Shipping shipping,
                                                          @AuthenticationPrincipal User user) {
        if (null == user) {
            return new ResponseEntity<>(UniformResponse.createForError("未登录"), HttpStatus.UNAUTHORIZED);
        } else {
            if (null == shipping ||
                    null == shipping.getUserId() ||
                    null == shipping.getAddressName() ||
                    null == shipping.getAddressMobile() ||
                    null == shipping.getAddressProvince() ||
                    null == shipping.getAddressCity() ||
                    null == shipping.getAddressDistrict() ||
                    null == shipping.getAddressDetail() ||
                    null == shipping.getAddressZip()) {
                return new ResponseEntity<>(UniformResponse.createForError("信息不足"), HttpStatus.BAD_REQUEST);
            } else {
                shipping.setId(null);
                shipping.setUserId(user.getId());
                boolean flag = shippingService.save(shipping);
                if (flag) {
                    return new ResponseEntity<>(UniformResponse.createForSuccess(shipping), HttpStatus.CREATED);
                } else {
                    return new ResponseEntity<>(UniformResponse.createForError("创建失败"), HttpStatus.INTERNAL_SERVER_ERROR);
                }
            }
        }
    }

    /**
     * 通过Shipping对象更新收货信息
     *
     * @param shipping id, userId不可为空
     * @return 未登录的错误信息；必选属性为空的错误信息；更新成功的Shipping对象；更新失败的错误信息
     */
    @PutMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<UniformResponse<Shipping>> put(@RequestBody Shipping shipping,
                                                         @AuthenticationPrincipal User user) {
        if (null == user) {
            return new ResponseEntity<>(UniformResponse.createForError("未登录"), HttpStatus.UNAUTHORIZED);
        } else if (null == shipping.getId() || null == shipping.getUserId()) {
            return new ResponseEntity<>(UniformResponse.createForError("信息不足"), HttpStatus.BAD_REQUEST);
        } else {
            shipping.setUpdateTime(LocalDateTime.now());
            boolean flag = shippingService.update(shipping, new QueryWrapper<Shipping>()
                    .eq("id", shipping.getId())
                    .eq("user_id", user.getId())
                    .ne("status", ItemStatus.DISABLE.getValue()));
            if (flag) {
                return new ResponseEntity<>(UniformResponse.createForSuccess(shipping), HttpStatus.RESET_CONTENT);
            } else {
                return new ResponseEntity<>(UniformResponse.createForError("更新失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

    /**
     * 通过id更新收货信息
     *
     * @param id 收货信息id
     * @return 未登录的错误信息；必选属性为空的错误信息；删除成功的信息；删除失败的错误信息
     */
    @DeleteMapping(value = "{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> delete(@PathVariable(value = "id") Integer id,
                                                          @AuthenticationPrincipal User user) {
        if (null == id) {
            return new ResponseEntity<>(UniformResponse.createForError("信息不足"), HttpStatus.BAD_REQUEST);
        } else if (null == user || null == user.getId() ||
                !user.getId().equals(shippingService.getById(id).getUserId())) {
            return new ResponseEntity<>(UniformResponse.createForError("未登录"), HttpStatus.UNAUTHORIZED);
        } else {
            Shipping shipping = new Shipping();
            shipping.setStatus(ItemStatus.DISABLE.getValue());
            shipping.setUpdateTime(LocalDateTime.now());
            boolean flag = shippingService.updateById(shipping);
            if (flag) {
                return new ResponseEntity<>(UniformResponse.createForSuccess(null), HttpStatus.RESET_CONTENT);
            } else {
                return new ResponseEntity<>(UniformResponse.createForError("删除失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

}
